package com.softstao.guoyu.ui.activity.me;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itheima.wheelpicker.WheelPicker;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.me.Address;
import com.softstao.guoyu.model.me.AddressCondition;
import com.softstao.guoyu.model.me.AddressList;
import com.softstao.guoyu.model.me.Area;
import com.softstao.guoyu.model.me.AreaList;
import com.softstao.guoyu.mvp.interactor.me.AddressInteractor;
import com.softstao.guoyu.mvp.presenter.me.AddressPresenter;
import com.softstao.guoyu.mvp.viewer.LinkProvinceCityViewer;
import com.softstao.guoyu.mvp.viewer.me.AddressViewer;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/22.
 */

public class AddAddressActivity extends BaseActivity implements AddressViewer,LinkProvinceCityViewer{

    @AIPresenter(presenter = AddressPresenter.class,interactor = AddressInteractor.class)
    AddressPresenter presenter;

    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.mobile)
    EditText mobile;
    @BindView(R.id.area)
    TextView areaView;
    @BindView(R.id.address_detail)
    EditText addressDetail;
    @BindView(R.id.loading)
    RelativeLayout loading;
    private AddressCondition condition = new AddressCondition();
    private Address address;
    private int flag=0;
    private boolean isCart =false;
    private String code = "0";
    private List<Area> provinceList = new ArrayList<>();
    private List<Area> cityList = new ArrayList<>();
    private List<Area> areaLists = new ArrayList<>();
    private String[] PROVINCES,CITYS,AREAS;
    private PopupWindow popupWindow;
    private int Selected = 0;
    private String provinceCode,cityCode,areaCode,province,city,area;

    @Override
    public int _ContentView() {
        return R.layout.activity_add_address;
    }

    @Override
    public void initView() {
        flag = getIntent().getIntExtra("flag",0);
        isCart = getIntent().getBooleanExtra("cart",false);
        address = (Address) getIntent().getSerializableExtra("address");
        if(flag==1) {
            initTitle("填写收货地址");
//            name.setText(UserManager.getInstance().getUser().getName());
//            mobile.setText(UserManager.getInstance().getUser().getMobile());
        }else if(flag==0){
            initTitle("编辑收货地址");
            name.setText(address.getName());
            mobile.setText(address.getMobile());
            areaView.setText(address.getProvinceName()+address.getCityName()+address.getAreaName());
            addressDetail.setText(address.getAddress());
            provinceCode = address.getProvinceCode();
        }

    }

    @OnClick({R.id.submit_btn, R.id.area})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.submit_btn:
                if(!check()){
                    return;
                }
                addAddress();
                break;
            case R.id.area:
                chooseProvince();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getArea();
    }

    private void chooseProvince(){
        View contentView = LayoutInflater.from(this).inflate(R.layout.layout_choose_address, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(66000000));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.showAtLocation(contentView.getRootView(), Gravity.BOTTOM, 0, 0);
        WheelPicker wheelView = (WheelPicker) contentView.findViewById(R.id.dialog_msg);
        wheelView.setData(Arrays.asList(PROVINCES));
        if (provinceCode!=null) {
            for (int i = 0; i < provinceList.size(); i++) {
                if (provinceList.get(i).getCode().equals(provinceCode)) {
                    this.Selected = i;
                }
            }
            wheelView.setSelectedItemPosition(Selected);
        }
        View otherView = contentView.findViewById(R.id.other_view);
        otherView.setOnClickListener(v ->
                popupWindow.dismiss()
        );
        TextView submitBtn = (TextView) contentView.findViewById(R.id.submit);
        submitBtn.setOnClickListener(v -> {
            province = PROVINCES[wheelView.getCurrentItemPosition()];
            provinceCode = provinceList.get(wheelView.getCurrentItemPosition()).getCode();
            code = provinceCode;
            this.Selected = wheelView.getCurrentItemPosition();
            cityCode = "";
            getArea();
            popupWindow.dismiss();
        });
    }

    private void chooseArea(int i){
        View contentView = LayoutInflater.from(this).inflate(R.layout.layout_choose_address, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(66000000));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.showAtLocation(contentView.getRootView(), Gravity.BOTTOM, 0, 0);
        WheelPicker wheelView = (WheelPicker) contentView.findViewById(R.id.dialog_msg);
        wheelView.setData(Arrays.asList(AREAS));
        View otherView = contentView.findViewById(R.id.other_view);
        otherView.setOnClickListener(v -> popupWindow.dismiss());
        TextView submitBtn = (TextView) contentView.findViewById(R.id.submit);
        submitBtn.setOnClickListener(v -> {
            switch (i){
                case 0:
                    city = AREAS[wheelView.getCurrentItemPosition()];
                    cityCode = areaLists.get(wheelView.getCurrentItemPosition()).getCode();
                    code = cityCode;
                    this.Selected = wheelView.getCurrentItemPosition();
                    getArea();
                    break;
                case 1:
                    area = AREAS[wheelView.getCurrentItemPosition()];
                    areaCode = areaLists.get(wheelView.getCurrentItemPosition()).getCode();
                    areaView.setText(province+city+area);
                    if (flag==1) {
                        condition.setProvinceCode(provinceCode);
                        condition.setCityCode(cityCode);
                        condition.setAreaCode(areaCode);
                    }else {
                        address.setProvinceCode(provinceCode);
                        address.setCityCode(cityCode);
                        address.setAreaCode(areaCode);
                    }
                    break;
            }
            popupWindow.dismiss();
        });
    }

    @Override
    public void addAddress() {
        condition.setAgentId(SharePreferenceManager.getInstance().getAgentId());
        if (flag==0){
            condition.setAddressId(address.getAddressId()+"");
            condition.setProvinceCode(address.getProvinceCode());
            condition.setCityCode(address.getCityCode());
            condition.setAreaCode(address.getAreaCode());
        }
        condition.setName(name.getText().toString());
        condition.setMobile(mobile.getText().toString());
        condition.setAddress(addressDetail.getText().toString());
        presenter.addAddress(condition);
    }

    @Override
    public void addResult(AddressList addressList) {
        if (flag==1){
            LZToast.getInstance(context).showToast("添加成功");
            if(isCart){
                Intent intent = getIntent();
                Bundle bundle = intent.getExtras();
                bundle.putSerializable("address",addressList.getAddressList().get(0));
                intent.putExtras(bundle);
                setResult(RESULT_OK,intent);
            }
        }else if (flag==0){
            LZToast.getInstance(context).showToast("编辑成功");
        }
        finish();
    }

    private boolean check(){
        if(TextUtils.isEmpty(name.getText().toString())){
            LZToast.getInstance(context).showToast("请输入姓名");
            return false;
        }if(TextUtils.isEmpty(mobile.getText().toString())){
            LZToast.getInstance(context).showToast("请输入手机号码");
            return false;
        }if(TextUtils.isEmpty(areaView.getText().toString())){
            LZToast.getInstance(context).showToast("请选择所在地区");
            return false;
        }if(TextUtils.isEmpty(addressDetail.getText().toString())) {
            LZToast.getInstance(context).showToast("请输入详细地址");
            return false;
        }
        return true;
    }

    @Override
    public void getArea() {
        presenter.getArea(code);
    }

    @Override
    public void getResult(AreaList areaList) {
        if (areaList!=null) {
            if (areaList.getList()!=null&&areaList.getList().size()!=0) {
                if (code.equals("0")) {
                    PROVINCES = new String[areaList.getList().size()];
                    provinceList.clear();
                    provinceList.addAll(areaList.getList());
                    for (int i = 0; i < provinceList.size(); i++) {
                        PROVINCES[i] = provinceList.get(i).getName();
                    }
                }else {
                    AREAS = new String[areaList.getList().size()];
                    areaLists.clear();
                    areaLists.addAll(areaList.getList());
                    for (int i = 0; i < areaLists.size(); i++) {
                        AREAS[i] = areaLists.get(i).getName();
                    }
                    if (cityCode.equals("")) {
                        chooseArea(0);
                    }else {
                        chooseArea(1);
                    }
                }
            }
        }
    }
}
